﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NDesk.Options;
using ExcelXmlConverter.Utils;
using System.Data;
using System.IO;

namespace ExcelXmlConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                List<string> inputs = new List<string>();
                List<string> outputs = new List<string>();

                var p = new OptionSet()
                {
                    {"in|input=", "the input file.", x=>inputs.Add(x)},
                    {"out|output=", "the output file.", x=>outputs.Add(x)}
                };

                List<string> extra = p.Parse(args);

                if (extra.Count > 0) throw new FormatException("parameters error");
                if (!PathsExist(inputs)) throw new Exception("there are inlegal input path");
                if (!FoldersExist(outputs)) throw new Exception("there are inlegal output path");

                DataSet dataset = new DataSet();
                foreach (string input in inputs)
                {
                    string text = File.ReadAllText(input);
                    DataTable table = XmlUtil.DeserializeDataTable(text);
                    table.TableName = Path.GetFileNameWithoutExtension(input);
                    dataset.Tables.Add(table);
                }

                foreach (string output in outputs)
                {
                    ExcelUtil.DataSetToExcel(dataset, output);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("----------------------------------------");
                Console.WriteLine("Usage eg : ExcelXmlConverter /in inputpath1 /in inputpath2 /out outputpath3");
                Console.WriteLine("----------------------------------------");
            }
        }

        private static bool PathsExist(List<string> inputs)
        {
            return inputs.All(p => File.Exists(p));
        }
        private static bool FoldersExist(List<string> inputs)
        {
            return inputs.All(p => Directory.Exists(Path.GetDirectoryName(p)));
        }
    }
}
